<template>
    <div class="box w-100 h-100 position-relative">
        <div class="pathtitle">{{ name }}</div>
        <!-- <div class="buttonbox flex flex-column align-center justify-center" v-if="showButton">
            <el-button @click="drawer = true" type="primary" style="margin-left: 100px"> 历史台风 </el-button>
        </div> -->
        <div class="sign" v-show="showButton">蓬江区水旱灾害防御分析预警平台</div>
        <div class="legend align-center justify-center flex" v-show="showButton">
            <div class="text"></div>
            <div class="box flex">
                <div class="item flex position-relative align-center justify-center" v-for="(item,i) in windSpeed" :key="i"><div class="circle" :style="`background-color:${item.color}`"></div>{{item.name}}</div>
            </div>
        </div>
        <div class="maptest">
            <div id="mapDiv" style="position: absolute; width: 100%; height: 100%"></div>
        </div>

        <div id="svgbox">
            <svg class="svg" height="200px" width="200px">
                <path
                    class="leaflet-clickable"
                    d="M60,0,A100,100,0,0,1,160,100,A100,100,0,0,1,60,200,L60,160,A60,60,0,0,1,0,100,A60,60,0,0,1,60,40,z"
                    fill="rgba(255,195,0,0.3)"
                    fill-rule="evenodd"
                    stroke="#F4D000"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-opacity="1"
                    stroke-width="1"
                ></path>
            </svg>
            <svg aria-hidden="true" class="icon">
                <use xlink:href="#icon-taifeng1"></use>
            </svg>
        </div>

        <el-drawer class="table_css" title="" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
            <el-table :data="datas" height="100%" border style="width: 100%" @row-click="rowClick">
                <el-table-column prop="tsid.tscname" label="台风名称" width="180" align="center"> </el-table-column>
                <el-table-column prop="tfskList[0].windspeed" label="最新风速（m/s）" align="center"></el-table-column>
                <el-table-column prop="tsid.crttime" label="开始时间" width="180" align="center"> </el-table-column>
                <el-table-column prop="tfskList[0].ddatetime" label="更新时间" align="center"> </el-table-column>
                <el-table-column prop="address" label="是否结束" align="center"></el-table-column>
            </el-table>
        </el-drawer>
    </div>
</template>

<script>
import { fetchRawData } from '@/api/weather_api'
//   import htmlToImage from 'html-to-image'
export default {
    data() {
        return {
            name: '',
            map: null,
            datas: [],
            showDatas: [],
            // mark: null,
            mark1: [],
            // 风圈覆盖物
            mark2: [],
            carTrack: [],
            lineArr: [],
            markers: [],
            infoWindow: [],
            zoom: null,
            tydata: null,
            //  警戒线坐标数据
            warnLineTrack: [],
            earlyWarnLine: [
                {
                    key: 24,
                    name: '24小时警戒线',
                    color: 'red',
                    list: [
                        [105, 0],
                        [113, 4.5],
                        [119, 11],
                        [119, 18],
                        [127, 22],
                        [127, 34]
                    ]
                },
                {
                    key: 48,
                    name: '48小时警戒线',
                    color: 'yellow',
                    list: [
                        [105, 0],
                        [120, 0],
                        [132, 15],
                        [132, 34]
                    ]
                }
            ],
            windSpeed: [
                // {
                //     name: '无风',
                //     describe: '陆地烟直上，海面平静',
                //     min: 0,
                //     max: 0.2,
                //     color: 'blue'
                // },
                // {
                //     name: '软风',
                //     describe: '烟示风向微波峰无飞沫',
                //     min: 0.3,
                //     max: 1.5,
                //     color: 'blue'
                // },
                // {
                //     name: '轻风',
                //     describe: '感觉有风	小波峰未破碎',
                //     min: 1.6,
                //     max: 3.3,
                //     color: 'blue'
                // },
                // {
                //     name: '微风',
                //     describe: '旌旗展开	小波峰顶破裂',
                //     min: 3.4,
                //     max: 5.4,
                //     color: 'blue'
                // },
                // {
                //     name: '和风',
                //     describe: '吹起尘土	小浪白沫波峰',
                //     min: 5.5,
                //     max: 7.9,
                //     color: 'blue'
                // },
                // {
                //     name: '轻劲风',
                //     describe: '小树摇摆	中浪折沫峰群',
                //     min: 8.0,
                //     max: 10.7,
                //     color: 'blue'
                // },
                // {
                //     name: '强风',
                //     describe: '电线有声	大浪到个飞沫',
                //     min: 10.8,
                //     max: 13.8,
                //     color: 'blue'
                // },
                // {
                //     name: '疾风',
                //     describe: '步行困难	破峰白沫成条',
                //     min: 13.9,
                //     max: 17.1,
                //     color: 'blue'
                // },
                // {
                //     name: '大风',
                //     describe: '折毁树枝	浪长高有浪花',
                //     min: 17.2,
                //     max: 20.7,
                //     color: 'blue'
                // },
                {
                    name: '烈风以下',
                    describe: '小损房屋	浪峰倒卷',
                    min: 0,
                    max: 24.4,
                    color: 'blue'
                },
                {
                    name: '狂风',
                    describe: '拔起树木	海浪翻滚咆哮',
                    min: 24.5,
                    max: 28.4,
                    color: '#FDAC03'
                },
                {
                    name: '暴风',
                    describe: '损毁普遍	波峰全呈飞沫',
                    min: 28.5,
                    max: 32.6,
                    color: '#EB180A'
                },
                {
                    name: '飓风',
                    describe: '摧毁巨大	海浪滔天',
                    min: 32.7,
                    max: null,
                    color: '#9F20D0'
                }
            ],
            showButton: true,
            drawer: false,
            direction: 'btt',
            activeNames: []
        }
    },
    methods: {
        rowClick(row) {
            // console.log(row);
            const i = this.showDatas.findIndex(item => item.tsid.tscname === row.tsid.tscname)
            i === -1 ? this.showDatas.push(row) : this.showDatas.splice(i, 1)
            this.remove_overlay()
            this.settf()
            this.setMarkers()
        },
        handleClose(done) {
            done()
        },
        handleChange(val) {
            console.log(val)
        },
        setMap() {
            var tile = new T.TileLayer(
                'http://t0.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=638555a1fe1e4268ffcf7e40ac240b53'
            )
            var tile1 = new T.TileLayer(
                'http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=638555a1fe1e4268ffcf7e40ac240b53'
            )
            var tile2 = new T.TileLayer(
                'http://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=638555a1fe1e4268ffcf7e40ac240b53'
            )
            this.map = new T.Map('mapDiv', { layers: [tile, tile1, tile2] })
            // this.map = new T.Map('mapDiv')
            const p = this.showDatas[0]?.tfskList[0]
            console.log(this.showDatas[0])
            const longitude = p !== undefined ? Number(p.longitude) : 113.080984
            const latitude = p !== undefined ? Number(p.latitude) : 22.574459
            this.map.centerAndZoom(new T.LngLat(longitude, latitude), 5)
        },

        settf() {
            this.zoom = this.map.getZoom()
            this.showDatas.forEach((e, i) => {
                // this.carTrack[i] = new T.CarTrack(this.map, {
                //       interval: 1,
                //       speed: 10,
                //       dynamicLine: false,
                //       polylinestyle: { color: '#35A7F6', weight: 3, opacity: 0.9 },
                //       Datas: e.tfskList.map(function (item) {
                //           return new T.LngLat(Number(item.longitude), Number(item.latitude))
                //       }),
                //       carstyle: { display: true, iconUrl: '', width: 0, height: 60 }
                //   })

                const points = []
                e?.tfskList.forEach((e, a) => {
                    points[a] = new T.LngLat(Number(e.longitude), Number(e.latitude))
                })
                this.lineArr[i] = new T.Polyline(points, {
                    weight: 3,
                    lineStyle: 'solid',
                    color: '#0000FF'
                })
                this.map.addOverLay(this.lineArr[i])
            })
        },
        //画警戒线
        setWarnLine() {
            this.earlyWarnLine.forEach((item, index) => {
                //画线
                const color = ['red', '#0000FF']
                const points = []
                item.list.forEach((e, a) => {
                    points[a] = new T.LngLat(e[0], e[1])
                })
                var line = new T.Polyline(points, {
                    weight: 2,
                    lineStyle: 'dashed',
                    color: color[index]
                })
                this.map.addOverLay(line)
                // 文本标注
                var label = new T.Label({
                    text: item.name,
                    offset: new T.Point(-5, -5),
                    position: new T.LngLat(item.list[item.list.length - 1][0], item.list[item.list.length - 1][1])
                })
                label.setFontColor(color[index])
                label.setBackgroundColor('transparent')
                label.getBorderLine(0)
                this.map.addOverLay(label)

                //画点
                // item.list.forEach(i=>{
                //   let TLngLat = new T.LngLat(i[0], i[1])
                //   let MarkerOptions = {
                //         icon: new T.Icon({
                //             iconUrl: require('./tf.png'),
                //             iconSize: new T.Point(8, 8),
                //             iconAnchor: new T.Point(4, 4)
                //         })
                //     }
                //   let markers = new T.Marker(TLngLat, MarkerOptions)
                //   this.map.addOverLay(markers)
                // })
            })
        },
        // 添加覆盖物
        setMarkers() {
            let svg = document.querySelector('.svg') // 获取 SVG 元素
            let xml = new XMLSerializer().serializeToString(svg) // 将 SVG 转换为字符串
            let dataUrl = 'data:image/svg+xml;base64,' + btoa(xml)

            this.showDatas.forEach((item, i) => {
                item['tfskList'].forEach((e, q) => {
                    let TLngLat = new T.LngLat(Number(e.longitude), Number(e.latitude))
                    const speed = Number(e.windspeed)

                    let color = ''
                    let describe = ''
                    let grade = ''

                    this.windSpeed.forEach(item => {
                        if (item.min <= speed && speed <= item.max) {
                            color = item.color
                            describe = item.describe
                            grade = item.name
                            console.log(color)
                            return
                        } else if (speed > 32.7) {
                            color = '#EB180A'
                            describe = item.describe
                            grade = item.name
                            return
                        } else {
                            return
                        }
                    })

                    // 覆盖物
                    this.markers.push([])
                    this.markers[i][q] = new T.Circle(
                        TLngLat, // 圆心坐标
                        5000, // 半径，单位：米
                        { color: color, fillColor: color, fillOpacity: 1, weight: 2 } // 样式选项
                    )

                    this.map.addOverLay(this.markers[i][q])

                    // 添加文字描述
                    const str = `风速：${e.windspeed}m/s&nbsp&nbsp&nbsp&nbsp名称：${item.tsid.tscname}<br>气压：${e.pressure}&nbsp&nbsp&nbsp&nbsp等级：${grade}<br>状态描述：${describe}<br>时间：${e.ddatetime}<br>`
                    this.infoWindow.push([])
                    this.infoWindow[i][q] = new T.InfoWindow(str, {
                        autoPan: true,
                        closeOnClick: true
                    })
                    this.markers[i][q].addEventListener('click', () => {
                        this.markers[i][q].openInfoWindow(this.infoWindow[i][q])
                    })
                })
                // 添加风圈
                let MarkerOptions2 = {
                    icon: new T.Icon({
                        iconUrl: dataUrl,
                        iconSize: new T.Point(100, 100),
                        iconAnchor: new T.Point(30, 50)
                    })
                }
                this.mark2[i] = new T.Marker(
                    new T.LngLat(Number(item['tfskList'][0].longitude), Number(item['tfskList'][0].latitude)),
                    MarkerOptions2
                )
                this.mark2[i].setZIndexOffset(-1)
                this.map.addOverLay(this.mark2[i])
                // this.mark1[i].setVisible(false)
                this.mark2[i].addEventListener('click', () => {
                    this.markers[i][0].openInfoWindow(this.infoWindow[i][0])
                })
                // 覆盖物
                // 台风动图
                let MarkerOptions3 = {
                    icon: new T.Icon({
                        iconUrl: require('./tf-1.gif'),
                        iconSize: new T.Point(30, 30),
                        iconAnchor: new T.Point(15, 15)
                    })
                }

                this.mark1[i] = new T.Marker(
                    new T.LngLat(Number(item['tfskList'][0].longitude), Number(item['tfskList'][0].latitude)),
                    MarkerOptions3
                )
                this.mark1[i].setZIndexOffset(9)
                this.map.addOverLay(this.mark1[i])
                this.mark1[i].addEventListener('click', () => {
                    this.markers[i][0].openInfoWindow(this.infoWindow[i][0])
                })
            })

            // this.map.addOverLay(this.mark)

            // 图标跟随zoom缩放
            this.map.addEventListener('zoomend', () => {
                this.zoom = this.map.getZoom()
                let scaleFactor = 0.2
                // let newWidth = 200 * this.zoom * scaleFactor
                // let newHeight = 200 * this.zoom * scaleFactor
                // let newWidth1 = 60 * this.zoom * scaleFactor
                // let newHeight1 = 100 * this.zoom * scaleFactor
                // let icon = this.mark.getIcon()
                // icon.setIconSize(new T.Point(newWidth, newHeight))
                // icon.setIconAnchor(new T.Point(newWidth1, newHeight1))
                // this.mark.setIcon(icon)

                this.mark2.forEach(e => {
                    let newWidth = 100 * this.zoom * scaleFactor
                    let newHeight = 100 * this.zoom * scaleFactor
                    let newWidth1 = 30 * this.zoom * scaleFactor
                    let newHeight1 = 50 * this.zoom * scaleFactor
                    let icon = e.getIcon()
                    icon.setIconSize(new T.Point(newWidth, newHeight))
                    icon.setIconAnchor(new T.Point(newWidth1, newHeight1))
                    e.setIcon(icon)
                })
            })
        },
        // 移除覆盖物
        remove_overlay() {
            this.markers.forEach(item => {
                item.forEach(i => {
                    this.map.removeOverLay(i)
                })
            })
            this.mark1.forEach(i => {
                this.map.removeOverLay(i)
            })
            this.mark2.forEach(i => {
                this.map.removeOverLay(i)
            })
            // this.carTrack.forEach(i=>{
            //     i.clear ()
            //   })
            this.lineArr.forEach(i => {
                this.map.removeOverLay(i)
            })
        },
        //判断按钮是否展示
        ifShowButton() {
            const dom = document.getElementById('mapDiv')
            dom.offsetWidth > 1000 ? (this.showButton = true) : (this.showButton = false)
        }
    },
    created() {},
    beforeMount() {},
    async mounted() {
        try {
            const data = await fetchRawData('TYPHOON')
            this.datas = JSON.parse(data)
            const nowTime = new Date().getTime()
            this.datas.forEach(item => {
                const time = new Date(item?.tfskList[0]?.ddatetime).getTime()
                const T = (nowTime - time) / 3600000
                T >= 24 ? '' : this.showDatas.push(item)
            })

            this.name = this.showDatas[0] ? this.showDatas[0].tsid.tscname : '当前无台风'
            this.setMap()
            this.settf()
            this.setMarkers()
            this.setWarnLine()

            // this.carTrack[2].clear()
        } catch (err) {
            console.error(err)
        }
        //this.ifShowButton()
    },
    watch: {}
}
</script>

<style lang="less" scoped>


::v-deep {
    .tdt-label,
    .tdt-label0,
    .tdt-label1 {
        white-space: normal !important;
        border: none;
        box-shadow: none;
    }
    .tdt-infowindow-content-wrapper {
        background-color: rgba(255, 255, 255, 0.8);
    }
    .tdt-infowindow-tip {
        background-color: rgba(255, 255, 255, 0.8);
    }
    .el-drawer__wrapper {
        position: absolute;
    }
    .el-drawer {
        color:#01B9F9;
        background-color: #a0b4dc;
        height: auto !important;
    }
    .el-drawer__body {
        // padding: 0 38px;
    }
    .el-collapse-item__header {
        padding: 0 20px;
        background-color: #a0b4dc;
        height: 35px;
    }
    .el-drawer__header {
        margin-bottom: 0;
        color: #024D91;
        padding: 0;
        height: 0;
    }
    .el-collapse-item__content {
        background-color: #a0b4dc;
    }
    .el-collapse-item__header.is-active {
        border-bottom-color: #ebeef5;
    }
    .el-table {
        height: auto;
    }
    .el-table__body-wrapper {
        height: auto !important;
    }
}
.buttonbox {
    position: absolute;
    z-index: 999;
    color: blue;
    left: 10px;
    top: 50px;
    width: 70px;
    font-size: 90%;
    font-weight: bold;
    .item {
        width: 100%;
        height: 25px;
        background-color: #dddddd;
        cursor: pointer;
    }
}
.pathtitle {
    position: absolute;
    top: 0;
    z-index: 999;
    color: red;
    left: 50%;
    font-size: 150%;
    transform: translate(-50%, 20%);
}
.svg {
    opacity: 0.5;
}
.box {
    width: 100%;
    height: 100%;
    .sign{
        position: absolute;
        z-index: 9999;
        right: 5px;
        font-size: 14px;
        bottom: 5px;
        color: #ffffff8f;
    }
    .legend{
        position: absolute;
        z-index: 9999;
        width: 0;
        font-size: 14px;
        height: 30px;
        background: #409EFF;
        bottom: 15px;
        left: 10px;
        .box{
            position: absolute;
            background: #ffffff83;
            left: 20px;
            width: 250px;
            height: 28px;
            // height: 60px;
            bottom: 0%;
            border-radius: 5px;
            // grid-template-columns: repeat(6,1fr);
            // padding: 0 0 0 15px;
            .item{
                margin-left:25px;
                color: black;
                div{
                color: black;

                }
            }
            .circle{
                position: absolute;
                width: 8px;
                height: 8px;
                background-color: red;
                left: -13px;
                border-radius: 50%;
                top: 40%;
            }
        }
    }
    .button {
        width: 100px;
        height: 35px;
        background-color: pink;
        z-index: 999;
        position: absolute;
        top: 20px;
        left: 50px;
        cursor: pointer;
    }
}

</style>